package org.lzy.shop.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.lzy.shop.base.BaseViewModel
import org.lzy.shop.network.KtorApiService
import org.lzy.shop.network.RefreshTokenRequest
import org.lzy.shop.network.RefreshTokenResponse
import org.lzy.shop.response.CreateMsgResponse
import org.lzy.shop.response.ItemMsg
import org.lzy.shop.response.MyInfoResponse
import org.lzy.shop.response.UserCountResponse
import org.lzy.shop.viewmodel.repository.MineRepository
import org.lzy.shop.viewmodel.repository.lmpl.MineRepositoryImpl

/**
 * 我的VM层
 */
class MineModel : BaseViewModel() {

    private val mineRepository: MineRepository = MineRepositoryImpl()

    // LiveData实例用于UI观察
    val myData = MutableLiveData<MyInfoResponse?>()

    val userCountData =MutableLiveData<UserCountResponse?>()

    val logoutData =MutableLiveData<Any?>()

    val createMsgData= MutableLiveData<CreateMsgResponse?>()

    val msgListData=MutableLiveData<MutableList<ItemMsg>?>()

    val sendMsgData =MutableLiveData<Any?>()


    /**
     * 获取用户个人信息
     */
    fun getMyInfo(): LiveData<MyInfoResponse?> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val result = mineRepository.getMyInfo()
                if (result != null) {
                    myData.value = result
                } else {
                    myData.value = null
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取个人信息失败"
                myData.value = null
            }
        }
        return myData
    }

    /**
     * 获取用户订单数量统计
     */
    fun getUserCount(): LiveData<UserCountResponse?> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val result = mineRepository.getUserCount()
                if (result != null) {
                    userCountData.value = result
                } else {
                    errorMessage.value = "获取订单数量失败"
                    userCountData.value = null
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取订单数量失败"
                userCountData.value = null
            }
        }
        return userCountData
    }

    /**
     * 用户登出
     */
    fun logout(): LiveData<Any?> {
        viewModelScope.launch {
            try {
                val result = mineRepository.logout()
                if (result != null) {
                    logoutData.value = result
                } else {
                    errorMessage.value = "登出失败"
                    logoutData.value = null
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "登出失败"
                logoutData.value = null
            }
        }
        return logoutData
    }

    /**
     * 创建消息会话
     */
    fun createMsg(): LiveData<CreateMsgResponse?> {
        viewModelScope.launch {
            try {
                val result = mineRepository.createMsg()
                if (result != null) {
                    createMsgData.value = result
                } else {
                    errorMessage.value = "创建会话失败"
                    createMsgData.value = null
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "创建会话失败"
                createMsgData.value = null
            }
        }
        return createMsgData
    }

    /**
     * 获取消息列表
     */
    fun getMsgList(sessionId: Int?, page: String?): LiveData<MutableList<ItemMsg>?> {
        viewModelScope.launch {
            try {
                val result = mineRepository.getMsgList(sessionId, page)
                if (result != null) {
                    msgListData.value = result
                } else {
                    errorMessage.value = "获取消息列表失败"
                    msgListData.value = null
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取消息列表失败"
                msgListData.value = null
            }
        }
        return msgListData
    }

    /**
     * 发送消息
     */
    fun sendMessage(sessionId: Int?, content: String): LiveData<Any?> {
        viewModelScope.launch {
            try {
                val result = mineRepository.sendMessage(sessionId, content)
                if (result != null) {
                    sendMsgData.value = result
                } else {
                    errorMessage.value = "发送消息失败"
                    sendMsgData.value = null
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "发送消息失败"
                sendMsgData.value = null
            }
        }
        return sendMsgData
    }

    /**
     * 刷新Token的方法
     */
    fun refreshToken(request: RefreshTokenRequest): LiveData<RefreshTokenResponse?> {
        val refreshResult = MutableLiveData<RefreshTokenResponse?>()

        viewModelScope.launch(Dispatchers.IO) {
            try {
                val result = KtorApiService.refreshToken(request)
                withContext(Dispatchers.Main) {
                    refreshResult.value = result
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    errorMessage.value = e.message ?: "刷新Token失败"
                    refreshResult.value = null
                }
            }
        }

        return refreshResult
    }

}